#include "StdAfx.h"
#include "Route.h"

using namespace Database;

RouteRow::RouteRow(void)
{
}

RouteRow::~RouteRow(void)
{
}

std::string RouteRow::getID() const
{
	return _id;
}

void RouteRow::setID(const std::string &id)
{
	_id = id;
}

std::string RouteRow::getName() const
{
	return _name;
}

void RouteRow::setName(const std::string &ne)
{
	_name = ne;
}

std::string RouteRow::getDirection() const
{
	return _direction;
}

void RouteRow::setDirection(const std::string &dn)
{
	_direction = dn;
}

RouteTable::RouteTable()
{
}

RouteTable::~RouteTable()
{
}

bool RouteTable::insert(const RouteRow &rr)
{
	MysqlExecute me;
	me.init(getLogin());

	std::string sql = "insert into route set "
		" id='" + rr.getID() + "', "
		" name='" + rr.getName() + "',"
		" direction='" + rr.getDirection() + "'";

	return me.execute(sql);
}

bool RouteTable::select(std::list<RouteRow> &rrs)
{
	std::string sql = "select id, name, direction"
		" from route";

	return select(sql, rrs);
}

bool RouteTable::selectOrderByNmae(std::list<RouteRow> &rrs)
{
	std::string sql = "select id, name, direction"
		" from route"
		" order by name";

	return select(sql, rrs);
}

bool RouteTable::updateByID(const RouteRow &rr)
{
	if (getLogin() == NULL)
	{
		return false;
	}

	MysqlExecute me;
	me.init(getLogin());

	std::string sql = "Update route set"
		" name='" + rr.getName() + "'"
		" direction='" + rr.getDirection() + "'"
		" where id='" + rr.getID() + "'";

	return me.execute(sql);
}

bool RouteTable::deleteByID(const RouteRow &rr)
{
	if (getLogin() == NULL)
	{
		return false;
	}

	MysqlExecute me;
	me.init(getLogin());
	std::string sql;

	sql = "delete from route"
		" where id='" + rr.getID() + "'";

	return me.execute(sql);
}

bool RouteTable::select(const std::string &sql, std::list<RouteRow> &rrs)
{
	if (getLogin() == NULL)
	{
		return false;
	}

	MysqlExecute me;
	me.init(getLogin());

	if (!me.execute(sql))
	{
		return false;
	}

	MysqlResult mr;
	char **v = mr.next(me.result());

	while (v != NULL)
	{
		RouteRow rr;

		int i = 0;
		rr.setID( toStr(v[i++]) );
		rr.setName( toStr(v[i++]) );
		rr.setDirection( toStr(v[i++]) );

		v = mr.next();

		rrs.push_back(rr);
	}

	return true;
}